In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.
In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
Make sure that you've downloaded the required human and dog datasets:
Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.
Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.
Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.
In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.
import os
import time
import numpy as np
from glob import glob
import cv2
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import models
import torchvision.models as models
from torchvision import datasets
import torchvision.transforms as T
#import torchvision.transforms as transforms
import torch.optim.lr_scheduler as scheduler
import torch.optim as optim
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import matplotlib.pyplot as plt
%matplotlib inline
# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))
# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.
OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.
In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.
We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Question 1: Use the code cell below to test the performance of the face_detector function.
human_files have a detected human face? dog_files have a detected human face? Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.
Answer:
Inspecting further on the images misclassified by the HAAR Cascase model, it would look like it was created using images from an American or European descent so a more diverse data set may yield better accuracy. This is of course a sensitive point in AI these days with various companies suspending facial recognition. Regardless, it's all a learning experience for me so I enjoyed it.
The keypoint model did not seem to have the same problem. While it wasn't able to detect faces in all images initially (1), I think that was a result of not being able to find the white part of the eyes as an example. Looking at two problematic images below, I believe this is likely why since the keypoint model uses a cnn and probably trained on specific features of the face. I didn't check the scores on these two so it's possible the threshold was just a bit higher that the score. Since this was an optional section, I'll go back and revisit later.
(1) As I mentioned initially the keypoint model wasn't able to detect all the faces, but by resizing the images, I achieved 100% of humans in the human data set. Additionally, by center cropping the images in the dog data set, I went from 22% to 11% in detecting humans. That is likely because humans tend to be on the side of their furry friend of which the dog is typically in the center of the picture. Regardless of 11%, about 2% of the 11% of those images did actually contain humans.
As I mentioned earlier here, I did some visual inspection to analyze the results from the two models.
I also tried various other methods to detect faces which I did not include in my writeup.
I decided to go with keypointrcnn_resnet50_fpn in pyTorch in the end since it had facial keypoints. I probably spent way too much time on this, but learned a lot. There are some additional comments in the following cells in this section.
human_files_short = human_files[:100]
dog_files_short = dog_files[:100]
#-#-# Do NOT modify the code above this line. #-#-#
from mpl_toolkits.axes_grid1 import ImageGrid
## TODO: Test the performance of the face_detector algorithm
## on the images in human_files_short and dog_files_short.
def detect_faces(image_set, humans_dataset=True):
human_count = 0
detected_list = list([])
image_set_size = len(image_set)
for index in range(image_set_size):
if face_detector(image_set[index]) == True:
human_count += 1
if humans_dataset == False:
detected_list.append(index)
else:
if humans_dataset:
detected_list.append(index)
return float((human_count / image_set_size) * 100), detected_list
humans_humans_percentage, humans_humans_list = detect_faces(human_files_short, True)
print(str(humans_humans_percentage) + "% of the time, there are humans in humans dataset.")
humans_dogs_percentage, humans_dogs_list = detect_faces(dog_files_short, False)
print(str(humans_dogs_percentage) + "% of the time, there are humans in dogs dataset.")
We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### COMPLETED: Test performance of another face detection algorithm.
### Feel free to use as many code cells as needed.
# define KEYPOINTRCNN_RESTNET50 model
KEYPOINTRCNN_RESTNET50 = models.detection.keypointrcnn_resnet50_fpn(pretrained=True)
KEYPOINTRCNN_RESTNET50.eval()
# check if CUDA is available
use_cuda = torch.cuda.is_available()
# move model to GPU if CUDA is available
if use_cuda:
KEYPOINTRCNN_RESTNET50 = KEYPOINTRCNN_RESTNET50.cuda()
print(KEYPOINTRCNN_RESTNET50)
THRESHOLD = 0.95
FACIAL_KEYPOINTS = 5
COCO_PERSON_KEYPOINT_NAMES = ['nose', 'left eye', 'right eye', 'left ear', 'right ear', 'left shoulder', 'right shoulder',
'left elbow', 'right elbow', 'left wrist', 'right wrist', 'left hip', 'right hip',
'left knee', 'right knee', 'left ankle', 'right ankle']
def KEYPOINTRCNN_RESTNET50_predict(img, humans_dataset):
# open image
img = Image.open(img).convert('RGB')
# depending on data set, use different transform
if humans_dataset:
transform = T.Compose([T.Resize(256), T.ToTensor()])
else:
transform = T.Compose([T.CenterCrop(224), T.ToTensor()])
# push img through transform
input_tensor = transform(img)
# create a mini-batch
batch = input_tensor.unsqueeze(0)
# move the batch to GPU; model already moved to GPU
if use_cuda:
batch = batch.cuda()
with torch.no_grad():
predictions = KEYPOINTRCNN_RESTNET50(batch)
return predictions[0]
def face_detector_keypoint(img, humans_dataset):
facial_features = False
predictions = KEYPOINTRCNN_RESTNET50_predict(img, humans_dataset)
scores = predictions['scores'].cpu().detach().numpy()
keypoints = predictions['keypoints'].to(torch.int16).cpu().numpy()[:, :2]
for score in scores:
if score < THRESHOLD:
continue
for idx, k in enumerate(keypoints[0:FACIAL_KEYPOINTS]):
facial_features = True
return facial_features
def detect_faces_keypoint(image_set, humans_dataset=True):
human_count = 0
detected_list = list([])
image_set_size = len(image_set)
for index in range(image_set_size):
if face_detector_keypoint(image_set[index], humans_dataset) == True:
human_count += 1
if humans_dataset == False:
detected_list.append(index)
else:
if humans_dataset:
detected_list.append(index)
return float((human_count / image_set_size) * 100), detected_list
humans_humans_percentage_keypoint, humans_humans_list_keypoint = detect_faces_keypoint(human_files_short, True)
print(str(humans_humans_percentage_keypoint) + "% of the time, there are humans in humans dataset.")
humans_dogs_percentage_keypoint, humans_dogs_list_keypoint = detect_faces_keypoint(dog_files_short, False)
print(str(humans_dogs_percentage_keypoint) + "% of the time, there are humans in dogs dataset.")
PADDING = 0.3
COLS = 6
FIGURE_SIZE_DIMENSION_FACTOR = 6.
def show_images(image_subset, image_set):
image_list_len = len(image_subset)
# validate list of images to show
if image_list_len == 0:
print("Image List is empty!")
return
# caclculate # of rows & cols to present images
rows = image_list_len // COLS
if image_list_len % COLS != 0:
rows += 1
fig_size_val = (FIGURE_SIZE_DIMENSION_FACTOR*rows, FIGURE_SIZE_DIMENSION_FACTOR*COLS)
fig = plt.figure(figsize=fig_size_val)
grid = ImageGrid(fig, 111, nrows_ncols=(rows, COLS), axes_pad=PADDING, cbar_set_cax=False)
for idx, (ax, im) in enumerate(zip(grid, image_subset)):
img = cv2.imread(image_set[image_subset[idx]])
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (50,50), interpolation = cv2.INTER_AREA)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Index: {}'.format(image_subset[idx]))
ax.imshow(img)
plt.show()
# HAAR Cascades
print("HAAR Cascades Image Grid of misclassified humans")
show_images(humans_humans_list, human_files_short)
print("HAAR Cascades Image Grid of misclassified dogs as humans")
show_images(humans_dogs_list, dog_files_short)
# keypointrcnn_resnet50_fpn
print("keypointrcnn_resnet50_fpn Image Grid of misclassified humans")
show_images(humans_humans_list_keypoint, human_files_short)
print("keypointrcnn_resnet50_fpn Image Grid of misclassified dogs as humans")
show_images(humans_dogs_list_keypoint, dog_files_short)
'''
Investigate if the different face detector algorithms have the same problem recognizing the same image
'''
def get_intersection_of_lists(list_a, list_b):
return list(set(list_a).intersection(list_b))
def compare_lists(list_a, list_b):
intersection_list = get_intersection_of_lists(list_a, list_b)
if len(intersection_list) > 0:
print(intersection_list)
else:
print("There aren't any images that are in both lists!")
print("Results with respect to the same image(s) misclassified by both models")
print("----------------------------------------------------------------------\n")
print("human data set:")
compare_lists(humans_humans_list, humans_humans_list_keypoint)
print("\ndog data set:")
compare_lists(humans_dogs_list, humans_dogs_list_keypoint)
HAAR_CASCADE_FRONTAL_FACE_FILE = 'haarcascades/haarcascade_frontalface_alt.xml'
'''
Display single image with ractangle around face(s)
'''
def show_face(image):
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier(HAAR_CASCADE_FRONTAL_FACE_FILE)
# load color (BGR) image
img = cv2.imread(image)
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.title("Faces detected: {}".format(len(faces)))
plt.imshow(cv_rgb)
plt.show()
# Show one of the images where a face wasn't detected by the HAAR Cascade
show_face(human_files_short[52])
def show_face_keypoint(img, humans_dataset):
predictions = KEYPOINTRCNN_RESTNET50_predict(img, humans_dataset)
detected_faces = 0
img = cv2.imread(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(16, 16))
fig, ax = plt.subplots(1, figsize=(16, 16))
for box, label, score, keypoints, keypoint_scores in zip(predictions['boxes'], predictions['labels'],
predictions['scores'], predictions['keypoints'],
predictions['keypoints_scores']):
# move data back to CPU
box = box.to(torch.int16).cpu().numpy()
label = label.cpu().detach().numpy()
score = score.cpu().detach().numpy()
keypoints = keypoints.to(torch.int16).cpu().numpy()[:, :2]
keypoint_scores = keypoint_scores.cpu().detach().numpy()
# if doesn't meet threshold, ignore
if score < THRESHOLD:
continue
cv2.rectangle(img, (box[0], box[1]), (box[2],box[3]),color=(0, 0, 255), thickness=1)
#cv2.putText(img,str('%.2f' % score), (box[0], box[1]), cv2.FONT_HERSHEY_SIMPLEX, 3, (255,128,255),thickness=3)
detected_faces += 1
print("Face {}".format(detected_faces))
for idx, k in enumerate(keypoints[0:FACIAL_KEYPOINTS]):
print("found {}".format(COCO_PERSON_KEYPOINT_NAMES[idx]))
#cv2.putText(img,COCO_PERSON_KEYPOINT_NAMES[idx], (k[0]-50, k[1]-25), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,128,255),thickness=2)
cv2.circle(img, (k[0], k[1]), radius=5, color=(0, 255, 0), thickness=-1)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title("Faces detected: {}".format(detected_faces))
ax.imshow(img)
# Show one of the images where a face wasn't detected by the HAAR Cascade, but was by the keypoint model
show_face_keypoint(human_files_short[52], True)
# Note: there's a bug I couldn't figure out where even though I only want to count faces via keypoints
# (COCO_PERSON_KEYPOINT_NAMES < 5 ), it seems to incorrectly detect those keypoints shown below. While there are
# correctly two people, there is only one face.
# Ok, let's look at some dog pics and see what we find...
# Sees 3 dog faces as humans and one other square which I'm not sure how that got classified.
show_face(dog_files_short[38])
# Better in terms of know where the person is, but no face and somehow finds a nose, eyes and ears...
show_face_keypoint(dog_files_short[38], False)
# Sees the human face correctly.
show_face(dog_files_short[63])
# Also sees the human face correctly. I wasn't why the skew in keypoints except that it may be the tensor
# img key points on the opencv img.
show_face_keypoint(dog_files_short[63], False)
# The keypoint model couldn't detect a face here...
show_face_keypoint(human_files_short[19], True)
# The keypoint model couldn't detect a face here either...
show_face_keypoint(human_files_short[61], True)
In this section, we use a pre-trained model to detect dogs in images.
The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.
# define VGG16 model
VGG16 = models.vgg16(pretrained=True)
# check if CUDA is available
use_cuda = torch.cuda.is_available()
# move model to GPU if CUDA is available
if use_cuda:
VGG16 = VGG16.cuda()
print(VGG16)
Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.
In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.
Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.
# Set PIL to be tolerant of image files that are truncated.
def VGG16_predict(img_path):
'''
Use pre-trained VGG-16 model to obtain index corresponding to
predicted ImageNet class for image at specified path
Args:
img_path: path to an image
Returns:
Index corresponding to VGG-16 model's prediction
'''
## TODO: Complete the function.
## Load and pre-process an image from the given img_path
## Return the *index* of the predicted class for that image
img = Image.open(img_path).convert('RGB')
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# compose transform to preprocess image
transform = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor(), normalize])
input_tensor = transform(img)
# create a mini-batch
batch = input_tensor.unsqueeze(0)
# move the batch to GPU; model already moved to GPU
if use_cuda:
batch = batch.cuda()
with torch.no_grad():
predictions = VGG16(batch)
# normalize the scores by running softmax to get probablilities
percentage = torch.nn.functional.softmax(predictions, dim=1)[0] * 100
# get the max probability
_, index = torch.max(predictions, 1)
# highest predicted class index
return index.cpu().numpy()[0]
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).
Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
## COMPLETED: Complete the function.
prediction = VGG16_predict(img_path)
return prediction > 150 and prediction < 269 # true/false
Question 2: Use the code cell below to test the performance of your dog_detector function.
human_files_short have a detected dog? dog_files_short have a detected dog?Answer:
0.0% of the time, there are dogs in humans dataset. 94.0% of the time, there are dogs in dogs dataset.
0.0% of the time, there are dogs in humans dataset. 95.0% of the time, there are dogs in dogs dataset.
0.0% of the time, there are dogs in humans dataset. 96.0% of the time, there are dogs in dogs dataset.
I didn't do as much analysis on the dog results since they were near 100%. Certainly the pretrained models have the expectation to predict with high accuracy given the research into the models and dataset as well as tuning the hyperparameters and such. From what I read, it's very common to use pretrained models in real-world scenarios (transfer learning) vs creating a new one from scratch.
### COMPLETED: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
def detect_dogs(image_set, dogs_dataset=True):
dog_count = 0
detected_list = list([])
image_set_size = len(image_set)
for index in range(image_set_size):
if dog_detector(image_set[index]) == True:
dog_count += 1
if dogs_dataset == False:
detected_list.append(index)
else:
if dogs_dataset:
detected_list.append(index)
return float((dog_count / image_set_size) * 100), detected_list
dogs_humans_percentage, dogs_humans_list = detect_dogs(human_files_short, False)
print(str(dogs_humans_percentage) + "% of the time, there are dogs in humans dataset.")
dogs_dogs_percentage, dogs_dogs_list = detect_dogs(dog_files_short, True)
print(str(dogs_dogs_percentage) + "% of the time, there are dogs in dogs dataset.")
We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.
# define RESNET50 model
RESNET50 = models.resnet50(pretrained=True)
RESNET50.eval()
# move model to GPU if CUDA is available
if use_cuda:
RESNET50 = RESNET50.cuda()
print(RESNET50)
def RESNET50_predict(img_path):
'''
Use pre-trained RESNET-50 model to obtain index corresponding to
predicted ImageNet class for image at specified path
Args:
img_path: path to an image
Returns:
Index corresponding to RESNET-50 model's prediction
'''
## COMPLETED: Complete the function.
## Load and pre-process an image from the given img_path
## Return the *index* of the predicted class for that image
img = Image.open(img_path).convert('RGB')
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# compose transform to preprocess image
transform = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor(), normalize])
input_tensor = transform(img)
batch = input_tensor.unsqueeze(0) # create a mini-batch
# move the batch to GPU; model already moved to GPU
if use_cuda:
batch = batch.cuda()
# push tensor through model for prediction
predictions = RESNET50(batch)
# normalize the scores by running softmax to get probablilities
percentage = torch.nn.functional.softmax(predictions, dim=1)[0] * 100
# get the max probability
_, index = torch.max(predictions, 1)
# highest predicted class index
return index.cpu().numpy()[0]
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector_resnet50(img_path):
## COMPLETED: Complete the function.
prediction = RESNET50_predict(img_path)
return prediction > 150 and prediction < 269
def detect_dogs_resnet50(image_set, dogs_dataset=True):
dog_count = 0
detected_list = list([])
image_set_size = len(image_set)
for index in range(image_set_size):
if dog_detector_resnet50(image_set[index]) == True:
dog_count += 1
if dogs_dataset == False:
detected_list.append(index)
else:
if dogs_dataset:
detected_list.append(index)
return float((dog_count / image_set_size) * 100), detected_list
dogs_humans_percentage_resnet50, dogs_humans_list_resnet50 = detect_dogs_resnet50(human_files_short, False)
print(str(dogs_humans_percentage_resnet50) + "% of the time, there are dogs in humans dataset.")
dogs_dogs_percentage_resnet50, dogs_dogs_list_resnet50 = detect_dogs_resnet50(dog_files_short, True)
print(str(dogs_dogs_percentage_resnet50) + "% of the time, there are dogs in dogs dataset.")
# define INCEPTIONV3 model
INCEPTIONV3 = models.inception_v3(pretrained=True)
INCEPTIONV3.eval()
# move model to GPU if CUDA is available
if use_cuda:
INCEPTIONV3 = INCEPTIONV3.cuda()
print(INCEPTIONV3)
def INCEPTIONV3_predict(img_path):
'''
Use pre-trained INCEPTION V3 model to obtain index corresponding to
predicted ImageNet class for image at specified path
Args:
img_path: path to an image
Returns:
Index corresponding to INCEPTION V3 model's prediction
'''
## COMPLETED: Complete the function.
## Load and pre-process an image from the given img_path
## Return the *index* of the predicted class for that image
img = Image.open(img_path).convert('RGB')
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# compose transform to preprocess image
transform = T.Compose([T.Resize(299), T.ToTensor(), normalize])
input_tensor = transform(img)
# create a mini-batch
batch = input_tensor.unsqueeze(0)
# move the batch to GPU; model already moved to GPU
if use_cuda:
batch = batch.cuda()
# push tensor through model for prediction
predictions = INCEPTIONV3(batch)
# normalize the scores by running softmax to get probablilities
percentage = torch.nn.functional.softmax(predictions, dim=1)[0] * 100
# get the max probability
_, index = torch.max(predictions, 1)
# highest predicted class index
return index.cpu().numpy()[0]
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector_inception_v3(img_path):
## COMPLETED: Complete the function.
prediction = INCEPTIONV3_predict(img_path)
return prediction > 150 and prediction < 269
def detect_dogs_inception_v3(image_set, dogs_dataset=True):
dog_count = 0
detected_list = list([])
image_set_size = len(image_set)
for index in range(image_set_size):
if dog_detector_inception_v3(image_set[index]) == True:
dog_count += 1
if dogs_dataset == False:
detected_list.append(index)
else:
if dogs_dataset:
detected_list.append(index)
return float((dog_count / image_set_size) * 100), detected_list
dogs_humans_percentage_inception_v3, dogs_humans_list_inception_v3 = detect_dogs_inception_v3(human_files_short, False)
print(str(dogs_humans_percentage_inception_v3) + "% of the time, there are dogs in humans dataset.")
dogs_dogs_percentage_inception_v3, dogs_dogs_list_inception_v3 = detect_dogs_inception_v3(dog_files_short, True)
print(str(dogs_dogs_percentage_inception_v3) + "% of the time, there are dogs in dogs dataset.")
Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
![]() |
![]() |
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
![]() |
![]() |
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
| Yellow Labrador | Chocolate Labrador | Black Labrador |
|---|---|---|
![]() |
![]() |
![]() |
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!
### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
data_dir = 'dogImages/'
train_dir = os.path.join(data_dir, 'train/')
valid_dir = os.path.join(data_dir, 'valid/')
test_dir = os.path.join(data_dir, 'test/')
import torch, gc
def torch_cleanup():
gc.collect()
torch.cuda.empty_cache()
torch_cleanup()
# Inception Takes 224x224 images as input, so we resize all of them
train_data_transform = T.Compose([T.RandomResizedCrop(224),
T.RandomHorizontalFlip(p=0.2),
#T.RandomAffine(30, translate=None, scale=None, shear=None, resample=False, fillcolor=0),
T.ColorJitter(brightness=0, contrast=0, saturation=0, hue=0),
T.RandomGrayscale(p=0.1),
#T.RandomPerspective(distortion_scale=0.5, p=0.5, interpolation=3, fill=0),
#T.RandomRotation(5, resample=False, expand=False, center=None, fill=None),
T.ToTensor()])
data_transform = T.Compose([T.Resize(size=(224,224)),
T.ToTensor()])
train_data = datasets.ImageFolder(train_dir, transform=train_data_transform)
valid_data = datasets.ImageFolder(valid_dir, transform=data_transform)
test_data = datasets.ImageFolder(test_dir, transform=data_transform)
# print out some data stats
print('Num training images: ', len(train_data))
print('Num validation images: ', len(valid_data))
print('Num test images: ', len(test_data))
# define dataloader parameters
batch_size = 32
num_workers=0
# prepare data loaders
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,
num_workers=num_workers, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid_data, batch_size=batch_size,
num_workers=num_workers, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size,
num_workers=num_workers, shuffle=True)
loaders_scratch = { 'train' : train_loader, 'valid' : valid_loader, 'test' : test_loader}
# Visualize some sample data
CLASSES = 133
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy() # convert images to numpy for display
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
for idx in np.arange(20):
ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
plt.imshow(np.transpose(images[idx], (1, 2, 0)))
ax.set_title(labels[idx].numpy())
Question 3: Describe your chosen procedure for preprocessing the data.
Answer: With regards to preprocessing the images, I resized the pictures to 224x224 which seems to be somewhat of a standard for color images(?). I know with grayscale images 32x32 seems to be ok given MNIST and Fashion-MNIST for a variety of reasons like keeping the number of parameters smaller, faster training/validation and tuning of hyperparameters. I started out with a number of random transforms, but in the end it added too much variation for the model to handle I believe. In general, I think it's better to keep it simple at the start and progress the overall tuning of model/parameters as we progress.
Create a CNN to classify dog breed. Use the template in the code cell below.
# define the CNN architecture
class Net(nn.Module):
### TODO: choose an architecture, and complete the class
def __init__(self):
super(Net, self).__init__()
## Define layers of a CNN
# convolutional layer
self.conv1 = nn.Conv2d(3, 32, 3, stride=2, padding=1)
self.bn1 = nn.BatchNorm2d(32)
# convolutional layer
self.conv2 = nn.Conv2d(32, 64, 3, stride=2, padding=1)
self.bn2 = nn.BatchNorm2d(64)
# convolutional layer
self.conv3 = nn.Conv2d(64, 128, 3, stride=1, padding=1)
self.bn3 = nn.BatchNorm2d(128)
# max pooling layer
self.pool = nn.MaxPool2d(2, 2)
# linear layer (7 * 7 * 128 -> 1024)
self.fc1 = nn.Linear(7 * 7 * 128, 1024)
# linear layer (1024 -> 133)
self.fc2 = nn.Linear(1024, CLASSES)
# dropout layer (p=0.05)
self.dropout = nn.Dropout2d(0.05)
# elu activation
self.elu = nn.ELU()
def forward(self, x):
## Define forward behavior
# (sees 224x224x3 image tensor as input)
x = self.elu(self.bn1(self.conv1(x)))
# (sees 112x112x32 tensor as input)
x = self.pool(x)
# (sees 56x56x32 tensor as input)
x = self.elu(self.bn2(self.conv2(x)))
# (sees 28x28x64 tensor as input)
x = self.pool(x)
# (sees 14x14x64 tensor as input)
x = self.elu(self.bn3(self.conv3(x)))
# (sees 14x14x128 tensor as input)
x = self.pool(x)
# Flatten x with start_dim=1 (sees 7x7x128 tensor as input)
x = torch.flatten(x, 1)
# add dropout layer
x = self.dropout(x)
# add 1st hidden layer, with elu activation function
x = self.elu(self.fc1(x))
# add dropout layer
x = self.dropout(x)
# add 1st hidden layer, with elu activation function
x = self.fc2(x)
return x
#-#-# You do NOT have to modify the code below this line. #-#-#
# instantiate the CNN
model_scratch = Net()
print(model_scratch)
# move tensors to GPU if CUDA is available
if use_cuda:
model_scratch.cuda()
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.
Answer: Overall, I was very humbled and completely understand why this is as much of an art as it is a science. I thought the 10% threshhold was quite low until I started seeing my results. I tried larger networks with up to 8 convolutional layers, but because of the number of parameters along with batch size, it was too much for my nVidia 1070. I had to scale it down which probably sacrificed accuracy. It makes perfect sense why using more complex pretrained models can yield better results. Additionally, I've used AWS and Google Colab for training and testing, but was never satisfied with any gain is speed that was supposed to be there. I haven't found it to be better than doing it on my local GPU. Event this notebook from start to finish takes about 4 hours!
With regards to my final model, I chose to use max pooling, batch normalization and dropout along with the convolutional and fully connected layers.
I used max pooling because it helps extract features like edges and helps prevent overfitting as well as reducing the spatial size and number of parameters. Average pooling for object detection isn't as good to extract features in this type of application.
I used batch normalization because it helps the model to learn more effectively and and therefore training faster. Another benefit is weight initialization is generally easier for deeper networks, but given this model is smaller - the benefit appears to be marginal from my testing. I acheived about 15% with or without this technique. I also found it was difficult to get anything higher than about 15% which suprised me. I'm curious as to why I couldn't even get a few percent (even up to 20% say). Nevertheless, I wanted to practice different methods here in this project.
I used dropout as another technique to prevent overfitting. It was a small amount as to not to overpenalize input layers or even a dependence of certain input layers. This then helps to improve generalization better.
With regards to hyperparameters - I chose to use batch size of 32, learning rate = 0.001, kept the epochs for this section at 100, varying stride to reduce parameters and used AdamW for the optimizer. Though throughout this project I tested various learning rates and optimizers, Adam/AdamW seems to do the best job learning. Using SGD with a learning rate scheduler (tried in transfer learning) seemed to achieve similar results, but took more epochs to get there.
Finally, the model I went with is:
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.
### TODO: select loss function
criterion_scratch = nn.CrossEntropyLoss()
### TODO: select optimizer
optimizer_scratch = optim.AdamW(model_scratch.parameters(), lr=0.001)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.
# the following import is required for training to be robust to truncated images
ImageFile.LOAD_TRUNCATED_IMAGES = True
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
"""returns trained model"""
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs+1):
# initialize variables to monitor training and validation loss
train_loss = 0.0
valid_loss = 0.0
class_correct = list(0. for i in range(CLASSES))
class_total = list(0. for i in range(CLASSES))
###################
# train the model #
###################
model.train()
for batch_idx, (data, target) in enumerate(loaders['train']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## find the loss and update the model parameters accordingly
# clear the gradients of all optimized variables
optimizer_scratch.zero_grad()
# forward pass: compute predicted outputs by passing inputs to the model
output = model_scratch(data)
# calculate the loss
loss = criterion_scratch(output, target)
# backward pass: compute gradient of the loss with respect to model parameters
loss.backward()
# perform a single optimization step (parameter update)
optimizer_scratch.step()
## record the average training loss, using something like
train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
#train_loss += loss.item()*data.size(0)
######################
# validate the model #
######################
model.eval()
for batch_idx, (data, target) in enumerate(loaders['valid']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## update the average validation loss
# forward pass: compute predicted outputs by passing inputs to the model
output = model_scratch(data)
# calculate the loss
loss = criterion_scratch(output, target)
# update running validation loss
valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
_, pred = torch.max(output, 1)
# compare predictions to true label
correct = np.squeeze(pred.eq(target.data.view_as(pred)))
# calculate test accuracy for each object class
for i in range(len(target)):
label = target.data[i]
class_correct[label] += correct[i].item()
class_total[label] += 1
valid_accuracy = 100. * np.sum(class_correct) / np.sum(class_total)
# print training/validation statistics
del data, target, output
torch.cuda.empty_cache()
print('Epoch: {} \tLoss: Train/Validation {:.6f}/{:.6f}\tValidation Acc: {:.2f}'.format(
epoch,
train_loss,
valid_loss,
valid_accuracy
))
## TODO: save the model if validation loss has decreased
if valid_loss <= valid_loss_min:
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
valid_loss))
torch.save(model_scratch.state_dict(), 'model_scratch.pt')
valid_loss_min = valid_loss
# return trained model
return model
# train the model
model_scratch = train(100, loaders_scratch, model_scratch, optimizer_scratch,
criterion_scratch, use_cuda, 'model_scratch.pt')
# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.
def test(loaders, model, criterion, use_cuda):
# monitor test loss and accuracy
test_loss = 0.
correct = 0.
total = 0.
model.eval()
for batch_idx, (data, target) in enumerate(loaders['test']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update average test loss
test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
# convert output probabilities to predicted class
pred = output.data.max(1, keepdim=True)[1]
# compare predictions to true label
correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
total += data.size(0)
print('Test Loss: {:.6f}\n'.format(test_loss))
print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
100. * correct / total, correct, total))
# call test function
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).
If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.
## TODO: Specify data loaders
# define training and test data directories
data_dir = 'dogImages/'
train_dir = os.path.join(data_dir, 'train/')
valid_dir = os.path.join(data_dir, 'valid/')
test_dir = os.path.join(data_dir, 'test/')
# Inception Takes 299x299 images as input, so we resize all of them
train_data_transform = T.Compose([T.RandomResizedCrop(299),
T.RandomHorizontalFlip(p=0.2),
T.RandomAffine(30, translate=None, scale=None, shear=None, resample=False, fillcolor=0),
T.ColorJitter(brightness=0, contrast=0, saturation=0, hue=0),
T.RandomGrayscale(p=0.1),
T.RandomPerspective(distortion_scale=0.5, p=0.5, interpolation=3, fill=0),
T.RandomRotation(5, resample=False, expand=False, center=None, fill=None),
T.ToTensor()])
data_transform = T.Compose([T.Resize(size=(299,299)),
T.ToTensor()])
train_data = datasets.ImageFolder(train_dir, transform=train_data_transform)
valid_data = datasets.ImageFolder(valid_dir, transform=data_transform)
test_data = datasets.ImageFolder(test_dir, transform=data_transform)
# print out some data stats
print('Num training images: ', len(train_data))
print('Num validation images: ', len(valid_data))
print('Num test images: ', len(test_data))
# define dataloader parameters
batch_size = 32
num_workers=0
# prepare data loaders
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,
num_workers=num_workers, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid_data, batch_size=batch_size,
num_workers=num_workers, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size,
num_workers=num_workers, shuffle=True)
# Visualize some sample data
CLASSES = 133
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy() # convert images to numpy for display
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
for idx in np.arange(20):
ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
plt.imshow(np.transpose(images[idx], (1, 2, 0)))
ax.set_title(labels[idx].numpy())
Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.
## TODO: Specify model architecture
model_transfer = models.inception_v3(pretrained=True)
model_transfer.aux_logits=False
# print out the model structure
print(model_transfer)
print(model_transfer.fc.in_features)
print(model_transfer.fc.out_features)
# Freeze training for all "features" layers
for param in model_transfer.parameters():
param.requires_grad = False
n_inputs = model_transfer.fc.in_features
# add last linear layer (n_inputs -> 133 dog classes)
# new layers automatically have requires_grad = True
last_layer = nn.Linear(n_inputs, CLASSES)
model_transfer.fc = last_layer
# if GPU is available, move the model to GPU
if use_cuda:
model_transfer = model_transfer.cuda()
# check to see that your last layer produces the expected number of outputs
print(model_transfer.fc.out_features)
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer: Based on my previous experimentation, I chose to use Inception V3 model. It has a more complex network architecture of which should be able to better detect subtleties in the different breeds. In the earlier section where I used pretrained models (VGG16, Resnet50 and Inception V3, Inception V3 did marginally better and is the reason I chose to continue using this model.
I did use many different transforms which probably increased the difficulty in learning, but since I'm using a pretrained model, I wanted to push the model to its limits to learn. You can see above the pictures after the random transforms like color jitter, flipping, grayscaling, etc..
Through experimentation, I chose to keep using AdamW with a learning rate of 0.001. Adam and Adamax performed nearly identical with Adamax seemed to continue learning after 10 epochs where Adam and AdamW seemed to quickly converge to the local minima after only 2-3 epochs. Adamax might perform better given more time. I typically stick with batch size of 32. I decided not to add any additional layers to the model because I wanted to see how it performs by itself. Given more time, I would explore this aspect.
Overall I achieved 70-75% accuracy so in general it's not too bad. Given more training with the current model, it will not improve accuracy so other modifications will be necessary.
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.
# try a bunch of different lr values and how it influences accuracy
#learning_rates = [0.01, 0.03, 0.001, 0.003, 0.0001]
#optimizer_names = ['Adadelta', 'ASGD', 'Adagrad', 'Adamax', 'Adam', 'AdamW']
#optimizers = list([])
#print(len(optimizers))
def generate_optimizersfor_model():
for learning_rate in learning_rates:
# try a bunch of different optimizers and how it influences accuracy
optimizers.append(optim.Adadelta(model_transfer.parameters(), lr=learning_rate))
optimizers.append(optim.ASGD(model_transfer.parameters(), lr=learning_rate))
optimizers.append(optim.Adagrad(model_transfer.parameters(), lr=learning_rate))
optimizers.append(optim.Adamax(model_transfer.parameters(), lr=learning_rate))
optimizers.append(optim.Adam(model_transfer.parameters(), lr=learning_rate))
optimizers.append(optim.AdamW(model_transfer.parameters(), lr=learning_rate))
criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = optim.AdamW(model_transfer.parameters(), lr=0.0001) #, amsgrad=True
#optimizer_transfer = torch.optim.SGD(model_transfer.parameters(), lr=0.001, momentum=0.9)
#scheduler_transfer = scheduler.ReduceLROnPlateau(optimizer_transfer, 'min')
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.
# train the model
#model_transfer = # train(n_epochs, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')
# number of epochs to train the model
n_epochs = 50
# move to pandas later
pt_state_dicts = list([])
train_losses, valid_losses, test_losses = list([]), list([]), list([])
valid_accuracies = list([])
def train(n_epochs, train_loader, valid_loader, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, model_transfer_name):
# initialize tracker for minimum validation loss
# set initial "min" to infinity
valid_loss_min = np.Inf
for epoch in range(n_epochs):
# monitor training loss
train_loss = 0.0
valid_loss = 0.0
train_start, train_end = 0.0, 0.0
valid_start, valid_end = 0.0, 0.0
class_correct = list(0. for i in range(CLASSES))
class_total = list(0. for i in range(CLASSES))
###################
# train the model #
###################
model_transfer.train() # prep model for training
for data, target in train_loader:
# move tensors to GPU if CUDA is available
if use_cuda:
data, target = data.cuda(), target.cuda()
train_start = time.time()
# clear the gradients of all optimized variables
optimizer_transfer.zero_grad()
# forward pass: compute predicted outputs by passing inputs to the model
output = model_transfer(data)
# calculate the loss
loss = criterion_transfer(output, target)
# backward pass: compute gradient of the loss with respect to model parameters
loss.backward()
# perform a single optimization step (parameter update)
optimizer_transfer.step()
# update running training loss
train_loss += loss.item()*data.size(0)
train_losses.append(train_loss/len(train_loader))
train_end = time.time()
######################
# validate the model #
######################
model_transfer.eval() # prep model for evaluation
for data, target in valid_loader:
# move tensors to GPU if CUDA is available
if use_cuda:
data, target = data.cuda(), target.cuda()
valid_start = time.time()
# forward pass: compute predicted outputs by passing inputs to the model
output = model_transfer(data)
# calculate the loss
loss = criterion_transfer(output, target)
# update running validation loss
valid_loss += loss.item()*data.size(0)
valid_losses.append(valid_loss/len(valid_loader))
_, pred = torch.max(output, 1)
# compare predictions to true label
correct = np.squeeze(pred.eq(target.data.view_as(pred)))
# calculate test accuracy for each object class
for i in range(len(target)):
label = target.data[i]
class_correct[label] += correct[i].item()
class_total[label] += 1
valid_end = time.time()
# print training/validation statistics
# calculate average loss over an epoch
train_loss = train_loss/len(train_loader.sampler)
valid_loss = valid_loss/len(valid_loader.sampler)
# used for SGD testing, but Adam/AdamW learned much faster (~10 vs 50 epochs)
#scheduler_transfer.step(valid_loss)
valid_accuracy = 100. * np.sum(class_correct) / np.sum(class_total)
valid_accuracies.append(valid_accuracy)
del data, target, output
torch.cuda.empty_cache()
print('Epoch: {} \tLoss: Train/Validation {:.6f}/{:.6f}\tValidation Acc: {:.2f}'.format(
epoch+1,
train_loss,
valid_loss,
valid_accuracy
))
# save model if validation loss has decreased
if valid_loss <= valid_loss_min:
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
valid_loss))
#model_at_epoch = 'model_' + str(epoch+1) + '.pt'
#model_at_epoch = model_transfer_name + '_e' + str(epoch+1) + '_tl' + str('{:.6f}').format(train_loss) + '_vl' + str('{:.6f}').format(valid_loss) + '.pt'
#torch.save(model_transfer.state_dict(), model_at_epoch)
#pt_state_dicts.append(model_at_epoch)
torch.save(model_transfer.state_dict(), 'model_transfer.pt')
valid_loss_min = valid_loss
del model_transfer
# load the model that got the best validation accuracy (uncomment the line below)
#model_transfer.load_state_dict(torch.load('model_transfer.pt'))
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.
#def test(n_epochs, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda):
test_acc = list([])
def test(model_transfer, criterion_transfer, use_cuda):
# initialize lists to monitor test loss and accuracy
test_loss = 0.0
class_correct = list(0. for i in range(CLASSES))
class_total = list(0. for i in range(CLASSES))
model_transfer.eval() # prep model for evaluation
for data, target in test_loader:
# move tensors to GPU if CUDA is available
if use_cuda:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model_transfer(data)
# calculate the loss
loss = criterion_transfer(output, target)
# update test loss
test_loss += loss.item()*data.size(0)
# convert output probabilities to predicted class
_, pred = torch.max(output, 1)
# compare predictions to true label
correct = np.squeeze(pred.eq(target.data.view_as(pred)))
# calculate test accuracy for each object class
for i in range(len(target)):
label = target.data[i]
class_correct[label] += correct[i].item()
class_total[label] += 1
del data, target, output, pred
torch.cuda.empty_cache()
# calculate and print avg test loss
test_loss = test_loss/len(test_loader.sampler)
test_losses.append(test_loss/len(test_loader))
print('Test Loss: {:.6f}\n'.format(test_loss))
test_accuracy = 100. * np.sum(class_correct) / np.sum(class_total), np.sum(class_correct), np.sum(class_total)
test_acc.append(test_accuracy)
for i in range(CLASSES):
if class_total[i] > 0:
print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (
str(i+1), 100 * class_correct[i] / class_total[i],
np.sum(class_correct[i]), np.sum(class_total[i])))
else:
print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i]))
print('\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % (test_accuracy))
#print(torch.cuda.memory_summary())
def find_best_model():
for idx, optimizer in enumerate(optimizers):
# construct model_transfer_name
lr_idx = idx % len(optimizer_names)
optimizer_idx = idx // len(optimizer_names)
model_transfer_name = optimizer_names[optimizer_idx] + '_lr' + str(learning_rates[lr_idx]).replace('0.', '')
print(model_transfer_name)
train(n_epochs, train_loader, valid_loader, model_transfer, optimizer, criterion_transfer, use_cuda, model_transfer_name)
pt_state_dict = pt_state_dicts[-1]
print(pt_state_dict)
state_dict = torch.load(pt_state_dict)
print(state_dict.keys())
model_transfer.load_state_dict(state_dict)
test(model_transfer, criterion_transfer, use_cuda)
#print(torch.cuda.memory_summary())
#state_dict = torch.load('model_transfer.pt')
#print(state_dict.keys())
#model_transfer.load_state_dict(state_dict)
train(n_epochs, train_loader, valid_loader, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'Adam_lr001')
#pt_state_dict = pt_state_dicts[-1]
#print(pt_state_dict)
state_dict = torch.load('model_transfer.pt')
print(state_dict.keys())
model_transfer.load_state_dict(state_dict)
test(model_transfer, criterion_transfer, use_cuda)
plt.plot(train_losses, label='Training loss')
plt.plot(valid_losses, label='Validation loss')
plt.plot(test_losses, label='Testing loss')
plt.legend(frameon=False)
Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
# list of class names by index, i.e. a name can be accessed like class_names[0]
class_names = [item[4:].replace("_", " ") for item in train_loader.dataset.classes]
#print(train_loader.dataset.classes)
def predict_breed_transfer(img_path):
img = Image.open(img_path).convert('RGB')
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# compose transform to preprocess image
transform = T.Compose([T.Resize(299), T.ToTensor(), normalize])
input_tensor = transform(img)
# create a mini-batch
batch = input_tensor.unsqueeze(0)
# push tensor through model for prediction
model = model_transfer.cpu()
model.eval()
output = model(batch)
idx = torch.argmax(output)
#_, pred = torch.max(output, 1)
#print(idx)
# highest predicted class index
return idx
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!

### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
from IPython.core.display import Image as displayImage
from IPython.core.display import display
def run_app(img_path):
display(displayImage(img_path,width=200,height=200))
## handle cases for a human face, dog, and neither
result = dog_detector_inception_v3(img_path)
if dog_detector_inception_v3(img_path) == True:
prediction = predict_breed_transfer(img_path)
print("hello furry friend, you are a {}".format(class_names[prediction]))
elif face_detector_keypoint(img_path, True) > 0:
prediction = predict_breed_transfer(img_path)
print("hello human, if you were a furry friend, you look like a {}".format(class_names[prediction]))
else:
print("hello, you don't look like a furry friend or a human...")
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: (Three possible points for improvement)
Overall, the app performed somewhat poorly actually even though the transfer learning model reports ~87% accuracy and was still learning even at 50 epochs. I think there must be some sort of corruption as I would expect better performance on this test data for breed. I definitely want to look into this later to better understand. Four areas I would improve upon are:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
human_files = ['human1.jpg', 'human2.jpg', 'cat1.jpg']
dog_files = ['Glen_of_imaal_terrier.jpg', 'german_Shepherd.jpg', 'black_lab.jpg']
## suggested code, below
for file in np.hstack((human_files[:3], dog_files[:3])):
run_app(file)